import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// 仪表盘数据
export interface DashboardData {
  stats: {
    textCount: number
    imageCount: number
    todayTexts: number
    todayImages: number
  }
  growth: Array<{
    date: string
    texts: number
    images: number
  }>
  distribution: Array<{
    type: string
    count: number
  }>
  recentLogs: Array<{
    id: string
    timestamp: string
    type: string
    status: string
    message: string
  }>
}

export const fetchDashboardData = async (): Promise<DashboardData> => {
  try {
    // 实际项目中这里应该是真实的 API 端点
    const response = await api.get<DashboardData>('/dashboard')
    return response
  } catch (error) {
    console.error('Failed to fetch dashboard data:', error)
    // 返回模拟数据作为 fallback
    return {
      stats: {
        textCount: 1243,
        imageCount: 567,
        todayTexts: 23,
        todayImages: 12
      },
      growth: [
        { date: '2023-05-01', texts: 100, images: 45 },
        { date: '2023-05-02', texts: 120, images: 50 },
        // 其他日期数据...
      ],
      distribution: [
        { type: '新闻', count: 450 },
        { type: '博客', count: 320 },
        // 其他类型数据...
      ],
      recentLogs: [
        {
          id: '1',
          timestamp: '2023-05-01 10:23:45',
          type: 'text',
          status: 'success',
          message: '成功爬取50条文本数据'
        },
        // 其他日志...
      ]
    }
  }
}

// 文本数据
export interface TextItem {
  id: string
  source: string
  crawlTime: string
  content: string
  url?: string
}

export const fetchTexts = async (params?: {
  page?: number
  size?: number
  search?: string
}): Promise<TextItem[]> => {
  try {
    const response = await api.get<TextItem[]>('/texts', { params })
    return response
  } catch (error) {
    console.error('Failed to fetch texts:', error)
    // 返回模拟数据作为 fallback
    return Array.from({ length: 20 }, (_, i) => ({
      id: `text-${i + 1}`,
      source: ['news', 'blog', 'forum'][Math.floor(Math.random() * 3)],
      crawlTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      content: `这是第${i + 1}条文本数据，包含一些示例内容。在实际应用中，这里会是真实的爬取到的文本内容。`.repeat(
        Math.ceil(Math.random() * 3)
      ),
      url: `https://example.com/article/${i + 1}`
    }))
  }
}

// 图片数据
export interface ImageItem {
  id: string
  filename: string
  source: string
  crawlTime: string
  url: string
  thumbnailUrl: string
  size?: number
  width?: number
  height?: number
}

export const fetchImages = async (params?: {
  page?: number
  size?: number
  search?: string
}): Promise<ImageItem[]> => {
  try {
    const response = await api.get<ImageItem[]>('/images', { params })
    return response
  } catch (error) {
    console.error('Failed to fetch images:', error)
    // 返回模拟数据作为 fallback
    return Array.from({ length: 20 }, (_, i) => ({
      id: `img-${i + 1}`,
      filename: `image-${i + 1}.jpg`,
      source: ['news', 'blog', 'forum'][Math.floor(Math.random() * 3)],
      crawlTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
      url: `https://picsum.photos/id/${i + 100}/800/600`,
      thumbnailUrl: `https://picsum.photos/id/${i + 100}/200/150`,
      size: Math.round(Math.random() * 1024 * 1024),
      width: 800,
      height: 600
    }))
  }
}

// 日志数据
export interface LogItem {
  id: string
  timestamp: string
  type: 'text' | 'image' | 'system' | 'error'
  status: 'success' | 'warning' | 'error' | 'info'
  message: string
  details?: string
}

export const fetchLogs = async (params?: {
  page?: number
  size?: number
  type?: string
  status?: string
}): Promise<LogItem[]> => {
  try {
    const response = await api.get<LogItem[]>('/logs', { params })
    return response
  } catch (error) {
    console.error('Failed to fetch logs:', error)
    // 返回模拟数据作为 fallback
    const types: LogItem['type'][] = ['text', 'image', 'system', 'error']
    const statuses: LogItem['status'][] = ['success', 'warning', 'error', 'info']
    
    return Array.from({ length: 50 }, (_, i) => ({
      id: `log-${i + 1}`,
      timestamp: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      type: types[Math.floor(Math.random() * types.length)],
      status: statuses[Math.floor(Math.random() * statuses.length)],
      message: `日志条目 ${i + 1}: ${['爬取成功', '存储失败', '网络错误', '任务完成'][Math.floor(Math.random() * 4)]}`,
      details: i % 3 === 0 ? '这里是额外的详细错误信息或堆栈跟踪' : undefined
    }))
  }
}